import json
import traceback
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def test(request):
    res = {"code": 200, "data": {}, "message": "Success"}
    try:
        params = request.GET if len(request.body) == 0 else json.loads(request.body)
            
        # 测试代码
        user_msg = params.get("msg", "")
        
        from openai import OpenAI
        client = OpenAI(api_key='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')

        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": "Who won the world series in 2020?"},
                {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
                {"role": "user", "content": user_msg}
            ]
        )
        resp_text = response.choices[0].message.content
        print(resp_text)
        res["data"] = resp_text
        
        pass
        
    except Exception as e:
        print(traceback.format_exc())
        res["code"] = 400
        res["message"] = "未知错误，请联系管理员"
    finally:
        return JsonResponse(res)
